package com.zihan.exception;

import com.zihan.domain.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler
    public Result exceptionHandler(BaseException ex){
        log.error("异常信息：{}", ex.getMessage());
        return Result.error(ex.getMessage());
    }


    @ExceptionHandler
    public Result exceptionHandler(SQLIntegrityConstraintViolationException ex) {
        String message = ex.getMessage();

        if (message.contains("Duplicate entry")) {
            String[] exceptMsg = message.split(" ");
            String res = exceptMsg[2];
            return Result.error(res+"已经存在");
        }
        log.error("异常信息：{}", ex.getMessage());
        return Result.error("未知异常");
    }
}
